package com.qriver.cloud.provider;

import com.sun.istack.internal.logging.Logger;
import org.apache.http.HttpStatus;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;


/**
 * 服务提供者
 */
@Controller
public class ProviderController {

    Logger logger = Logger.getLogger(ProviderController.class);

    private static int count = 0;

    @RequestMapping("/provider")
    @ResponseBody
    public String provider() {
        logger.info("调用ClientA的provider()方法！");
        return "ClientA服务 的provider()方法！";
    }

    @RequestMapping("/provider2")
    public void provider2(HttpServletRequest request, HttpServletResponse reponse) {
        try {
            reponse.setCharacterEncoding("utf-8");
            reponse.setContentType("text/html;charset=utf-8");
            Random random = new Random();
            int num = random.nextInt(9);
            logger.info("random:" + num);
            if (num % 4 == 0) {
                count = 0;
                logger.info("调用ClientA的provider2()方法！成功");
                reponse.setStatus(HttpStatus.SC_OK);
                PrintWriter pw = reponse.getWriter();
                pw.write("成功访问！");
                pw.flush();
            } else {
                count++;
                logger.info("调用ClientA的provider2()方法！失败，次数：" + count);
                reponse.setStatus(HttpStatus.SC_BAD_GATEWAY);
                PrintWriter pw = reponse.getWriter();
                pw.write("访问失败！");
                pw.flush();
            }
        } catch (Exception e) {
            logger.info(e.getMessage());
        }

    }


}
